#include <iostream>
#include <pthread.h>
#include <vector>
#include <string>
#include <unistd.h>
#include "mutex.hpp"
using namespace std;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

#define NUM 4

class threadData
{
public:
    threadData(int number /*,pthread_mutex_t* lock*/)
    {
        _threadname = "thread-" + to_string(number);
        // _lock = lock;
    }

public:
    string _threadname;
    // pthread_mutex_t* _lock;
};

int ticket = 1000;

// int num = 1000;//；临界资源

// void fun()
// {
//     while(1)
//     {
//         //临界区
//         if(num>0)
//         {
//             cout<<"num : " <<num<< endl;
//             num--;
//         }
//         //临界区
//     }
// }

void *getticket(void *argc)
{
    threadData *td = static_cast<threadData *>(argc);
    const char *name = td->_threadname.c_str();
    while (1)
    {
        // pthread_mutex_lock(td->_lock);
        // pthread_mutex_lock(&lock);
        //在下面的代码块作用域中利用局部变量_lock实现自动加锁释放锁
        {
            Lock _lock(&lock);
            if (ticket > 0)
            {
                usleep(1000);
                printf("who=%s,get a ticket : %d\n", name, ticket);
                ticket--;
                // pthread_mutex_unlock(td->_lock);
                // pthread_mutex_unlock(&lock);
            }
            else
            {
                // pthread_mutex_unlock(td->_lock);
                // pthread_mutex_unlock(&lock);
                break;
            }
        }
        usleep(50);
    }
    delete td;
    // printf("%s quit ...\n",name);
    return nullptr;
}

int main()
{
    vector<pthread_t> tids;
    vector<threadData *> thread_data;
    pthread_mutex_t lock;
    // pthread_mutex_init(&lock,nullptr);
    for (int i = 1; i <= NUM; i++)
    {
        pthread_t tid;
        threadData *td = new threadData(i /*,&lock*/);
        // thread_data.push_back(td);
        // pthread_create(&tid, nullptr, getticket, thread_data[i - 1]);
        pthread_create(&tid, nullptr, getticket, td);
        tids.push_back(tid);
    }

    for (auto thread : tids)
    {
        pthread_join(thread, nullptr);
    }

    // pthread_mutex_destroy(&lock);

    // for(auto td : thread_data)
    // {
    //     delete td;
    // }
    return 0;
}

// int main()
// {
//     //定义锁
//     pthread_mutex_t lock;
//     //初始化锁
//     pthread_mutex_init(&lock,nullptr);

//     //进行加锁操作

//     //销毁锁
//     pthread_mutex_destroy(&lock);
//     return 0;
// }

// //定义锁
// pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
// int main()
// {
//     //直接进行加锁操作

//     return 0;
// }